package com.zzc.legou.service.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzc.legou.core.service.impl.CrudServiceImpl;
import com.zzc.legou.item.entity.Sku;
import com.zzc.legou.item.entity.Spu;
import com.zzc.legou.item.entity.SpuDetail;

import com.zzc.legou.log.aop.annotation.LogAnno;
import com.zzc.legou.service.item.dao.SkuDao;
import com.zzc.legou.service.item.dao.SpuDetailDao;
import com.zzc.legou.service.item.service.ISpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SpuServiceImpl extends CrudServiceImpl<Spu> implements ISpuService {

    @Autowired
    private SpuDetailDao spuDetailDao;

    @Autowired
    private SkuDao skuDao;


    @LogAnno(description = "注册接口",type = "注册")
    @Override
    public void saveSpu(Spu spu) {
        Long id = spu.getId();
        //向spu表中插入数据
        this.saveOrUpdate(spu);;
        //向skus表中插入数据
        //需要删除原来的信息
        skuDao.delete(Wrappers.lambdaQuery(Sku.class).eq(Sku::getSpuId, id));
        List<Sku> skus = spu.getSkus();
        for (Sku sku : skus) {
            sku.setSpuId(id);
            skuDao.insert(sku);
        }

        SpuDetail spuDetail = spu.getSpuDetail();
        //如果当前的详细页面为空的情况
        if (ObjectUtils.isEmpty(spuDetail.getId())) {
            //添加详情信息
            spuDetail.setId(id);
            spuDetailDao.insert(spuDetail);
        } else {
            spuDetailDao.updateById(spuDetail);
        }

    }
}
